package cn.wsn2018.tools.util;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 精简化controller的逻辑，将一些固定的设置操作放到此工具类中
 * 将该类设置成线程安全的单例模式
 */
public class ServletUtil {

    private Logger logger = Logger.getLogger(ServletUtil.class);
    private static ServletUtil instance=null;
    private ServletUtil(){}
    /**
     * 得到单例的接口，确保只有一个实例
     * @return
     */
    public static ServletUtil getInstance(){
        if(instance==null){
            synchronized(ServletUtil.class){
                if(instance==null)
                    instance=new ServletUtil();
            }
        }
        return instance;
    }
    /**
     * 处理HttpResponse的一些设置和返回输出操作
     * @param response
     * @param jsonString 从service返回的json字符串
     * @throws Exception
     */
    public void responseOperating(HttpServletResponse response, String jsonString) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-type", "text/html; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.getWriter().write(jsonString);
    }

    /**
     * 处理HttpRequest的字符集设置操作
     * @param request
     * @throws Exception
     */
    public void requestOperating(HttpServletRequest request)throws Exception{
        request.setCharacterEncoding("utf-8");
    }
}
